package com.dingwen.treasure.open.api.baidu.map.service.impl;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.dingwen.treasure.open.api.baidu.map.bo.WeatherBo;
import com.dingwen.treasure.open.api.baidu.map.config.BaiduMapConfig;
import com.dingwen.treasure.open.api.baidu.map.service.BaiduMapService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.util.Assert;

import javax.annotation.Resource;

/**
 * 百度地图服务impl
 *
 * @author dingwen
 * @date 2022/12/29
 */
@Service
@Slf4j
public class BaiduMapServiceImpl implements BaiduMapService {

    @Resource
    private BaiduMapConfig mapConfig;

    @Override
    public WeatherBo queryWeather(String areaCode) {
        StringBuilder urlBuilder = new StringBuilder(mapConfig.getWeatherQueryUrl())
                .append("?")
                .append(DISTRICT_ID_KEY)
                .append("=")
                .append(areaCode)
                .append("&")
                .append(DATA_TYPE_KEY)
                .append("=")
                .append(mapConfig.getDataType())
                .append("&")
                .append(AK_KEY)
                .append("=")
                .append(mapConfig.getAk());
        String result = HttpUtil.get(urlBuilder.toString());
        Assert.isTrue(StrUtil.isNotBlank(result) && JSONUtil.isJson(result),"百度地图返回结果空或不是JSON");
        JSONObject re = JSONUtil.parseObj(result);
        Integer status = re.get(STATUS_KEY, Integer.class);
        if(!STATUS_SUCCESS.equals(status)){
            log.error("百度地图调用失败，详细信息{}",JSONUtil.toJsonStr(result));
           return null;
        }
        JSONObject data = re.get(RESULT_KEY, JSONObject.class);
        JSONObject location = data.get(LOCATION_KEY, JSONObject.class);
        Assert.notNull(location,"location信息获取空");
        String fullLocation = location.get(CITY_KEY,String.class)
                .concat(location.get(NAME_KEY,String.class));

        JSONArray forecasts = data.get(FORECASTS_KEY, JSONArray.class);
        Assert.isTrue(ObjectUtil.isNotEmpty(forecasts) && !forecasts.isEmpty(),"预报信息获取空");
        JSONObject nowDayWeather = forecasts.get(0, JSONObject.class);
        return WeatherBo.builder()
                .location(fullLocation)
                .weather(nowDayWeather.get(TEXT_DAY_KEY,String.class))
                .high(nowDayWeather.get(HIGH_KEY,String.class))
                .low(nowDayWeather.get(LOW_KEY,String.class))
                .build();
    }
}
